package com.huanglejing.shanggou.common;

import android.annotation.TargetApi;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.huanglejing.mylibrary.KLog;
import com.huanglejing.shanggou.R;
import com.huanglejing.shanggou.utils.C;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by Administrator on 2016/7/21 0021.
 */
public abstract class AppBaseActivity<P extends BasePresenter<V>, V extends BaseView> extends BaseActivity implements LoaderManager.LoaderCallbacks<P>, PresenterFactory<P>, BaseView {

    static final AtomicInteger sViewCounter = new AtomicInteger(Integer.MIN_VALUE);
    /**
     * Do we need to call {@link #doStart()} from the {@link #onLoadFinished(Loader, BasePresenter)} method.
     * Will be true if presenter wasn't loaded when {@link #onStart()} is reached
     */
    private final AtomicBoolean mNeedToCallStart = new AtomicBoolean(false);
    protected boolean mFirstStart;//Is this the first start of the activity (after onCreate)
    protected P mBasePresenter;

    @Nullable
    public CollapsingToolbarLayout toolbarLayout;
    protected View mRootView;
    protected @Nullable
    MaterialDialog placeLoading = null;
    private int mUniqueLoaderIdentifier;//Unique identifier for the loader, persisted across re-creation

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //  UIHelper.$optimizeBackgroundOverdraw(this);
        KLog.d(TAG, TAG + "=> onCreate_save:" + savedInstanceState);
        mFirstStart = savedInstanceState == null || savedInstanceState.getBoolean(C.SavedInstanceState.RECREATION_SAVED_STATE);
        mUniqueLoaderIdentifier = savedInstanceState == null ? AppBaseActivity.sViewCounter.incrementAndGet() : savedInstanceState.getInt(C.SavedInstanceState.LOADER_ID_SAVED_STATE);
        mRootView = getLayoutInflater().inflate(getLayoutId(), null);
        setContentView(mRootView);
        toolbarLayout = findViewById(R.id.toolbar_layout);
        getSupportLoaderManager().initLoader(mUniqueLoaderIdentifier, null, AppBaseActivity.this);
        try {
            if (findViewById(R.id.tv_title) != null && (TextView) findViewById(R.id.tv_title) != null) {
                setmTvTitle((TextView) findViewById(R.id.tv_title));
            }
            if (findViewById(R.id.iv_login_exit) != null && (ImageView) findViewById(R.id.iv_login_exit) != null) {
                setmIvExit((ImageView) findViewById(R.id.iv_login_exit));
                getmIvExit().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });
            }

        } catch (Exception e) {

        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mBasePresenter == null) {
            mNeedToCallStart.set(true);
        } else {
            doStart();
        }
    }

    protected void doStart() {
        KLog.d(TAG, TAG + "doStart", mFirstStart, mUniqueLoaderIdentifier);
        assert mBasePresenter != null;
        mBasePresenter.onViewAttached((V) this);
        mBasePresenter.onStart(mFirstStart);
        mFirstStart = false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mBasePresenter != null) mBasePresenter.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mBasePresenter != null) mBasePresenter.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mBasePresenter != null) {
            mBasePresenter.onStop();
        }
    }

    @Override
    protected void onDestroy() {
        if (mBasePresenter != null) {
            mBasePresenter.onViewDetached();
        }
        dismissLoading();
        super.onDestroy();

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean(C.SavedInstanceState.RECREATION_SAVED_STATE, true);
        outState.putInt(C.SavedInstanceState.LOADER_ID_SAVED_STATE, mUniqueLoaderIdentifier);
    }

    protected abstract int getLayoutId();

    /**
     * 不需要权限就忽略
     * 触发时机自己处理
     */
    @TargetApi(Build.VERSION_CODES.M)
    protected abstract void requestPermission();

    @Override
    public Loader<P> onCreateLoader(int id, Bundle args) {
        return new PresenterLoader<>(this, this);
    }

    @Override
    public void onLoadFinished(Loader<P> loader, P data) {
        mBasePresenter = data;
        if (mNeedToCallStart.compareAndSet(true, false)) {
            doStart();
        }
    }

    @Override
    public void onLoaderReset(Loader<P> loader) {
        mBasePresenter = null;
    }

    @Nullable
    public CollapsingToolbarLayout getToolbarLayout() {
        return toolbarLayout;
    }

    @Override
    public void showLoading() {
        try {
            View view = LayoutInflater.from(AppBaseActivity.this).inflate(R.layout.layout_loading_dialog, null);
            placeLoading = new MaterialDialog.Builder(getViewContext())
                    .itemsGravity(GravityEnum.CENTER)
                    .customView(view, true)
                    .cancelListener(new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            dialog.dismiss();
                            placeLoading = null;
                        }
                    })
                    .backgroundColor(Color.TRANSPARENT)
                    .cancelable(true)
                    .canceledOnTouchOutside(false)
                    .show();
        } catch (Exception e) {
        }
      /*  if (placeLoading != null) {
            placeLoading.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    showError(new Throwable());
                }
            });
        }*/
    }

    @Override
    public void dismissLoading() {
        try {
            if (placeLoading != null) {
                placeLoading.dismiss();
                placeLoading = null;
            }
        } catch (Exception e) {
        }
    }


}
